class Thought < ActiveRecord::Base
  #[TO-DO] add named scopes
  acts_as_taggable_on :tags
  belongs_to :author, :class_name => "User", :foreign_key => "author_id"
  acts_as_tree
  belongs_to :parent, :class_name => "Thought", :foreign_key => "parent_id", :counter_cache => "response_count"
  has_many :responses, :class_name => "Thought", :foreign_key => "parent_id"
  has_many :votes
  has_many :voters, :through => :votes, :source => :user

  def Thought.questions
    Thought.roots
  end 
  
  def childless?
    children.nil? || children.empty?
  end

  def readable_type
    if Thought.questions.include?(self)
      "question"
    else
      "response"
    end
  end
  def tally_votes
    new_score = self.votes.collect{|vote| vote.value}.sum
    update_attribute(:vote_score, new_score)
  end
  def authored_by?(user)
    return false unless user
    author_id == user.id
  end
end
